package org.fast.develop.logicflow.runtime.expression.el;

/**
 * 项 目 名：gs-tto-data-mapping
 * 源文件名：com.geekstorm.tto.datamapping.core.el.ReadOnlyMapELResolver
 * 文件版本：1.0.0
 * 创建人： 莫寅
 * 创建日期：2020-07-23 11:47
 * 修改作者：莫寅
 * 修改日期：2020-07-23 11:47
 * 文件描述：
 * By：2020 © CompanyName  , Inc. All Rights Reserved.
 */

import javax.el.ELContext;
import javax.el.ELResolver;
import java.beans.FeatureDescriptor;
import java.util.Iterator;
import java.util.Map;

/**
 * An {@link ELResolver} that exposed object values in the map, under the name of the
 * entry's key. The values in the map are only returned when requested property has no
 * 'base', meaning it's a root-object.
 *
 * @author Frederik Heremans
 */
public class ReadOnlyMapELResolver extends ELResolver {

	protected Map<Object, Object> wrappedMap;

	public ReadOnlyMapELResolver(Map<Object, Object> map) {
		this.wrappedMap = map;
	}

	@Override
	public Object getValue(ELContext context, Object base, Object property) {
		if (base == null) {
			if (wrappedMap.containsKey(property)) {
				context.setPropertyResolved(true);
				return wrappedMap.get(property);
			}
		}
		return null;
	}

	@Override
	public boolean isReadOnly(ELContext context, Object base, Object property) {
		return true;
	}

	@Override
	public void setValue(ELContext context, Object base, Object property, Object value) {
		if (base == null) {
			if (wrappedMap.containsKey(property)) {
				throw new IllegalArgumentException("Cannot set value of '" + property + "', it's readonly!");
			}
		}
	}

	@Override
	public Class<?> getCommonPropertyType(ELContext context, Object arg) {
		return Object.class;
	}

	@Override
	public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object arg) {
		return null;
	}

	@Override
	public Class<?> getType(ELContext context, Object arg1, Object arg2) {
		return Object.class;
	}

}
